<?php
/**
* All Scribble admin UIs must extends from this Controller.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
use Buan\Config;
use Buan\Controller;
use Buan\Core;
use Buan\Database;
use Buan\ModelManager;
use Buan\SystemLog;
use Buan\View;
class ScribbleAdminController extends Controller {

	/**
	* Deliver a generic "not found" page.
	*
	* @return ScribbleAdminView
	*/
	protected function error404() {
		header("HTTP/1.1 404");
		$view = new ScribbleAdminView();
		if(!$this->init($view, TRUE, TRUE)) {
			return $view;
		}
		$view->setSource(Config::get('ext.Scribble.dir.views').'/error-404.tpl.php');
		return $view;
	}

	/**
	* Authenticates the currently logged-in user to check they have permission to
	* access the admin interfaces. If not logged in then the $view source is set
	* to show the login form.
	*
	* We also check that the system is installed.
	*
	* All admin controller actions should call this method before allowing the
	* user to view the requested UI. For example:
	*
	* $view = new ScribbleAdminView();
	* if(!$this->init($view)) {
	*		return $view;
	* }
	*
	* @param ScribbleAdminView
	* @param bool If TRUE then the login check is bypassed
	* @return bool
	*/
	protected function init(ScribbleAdminView &$view, $bypassAuthCheck=FALSE) {

		// Setup the global view and add a reference to it in the $view
		$GV = ScribbleAdminView::getGlobalView();

		// Setup a dummy secondary view for UIs that don't use it
		$sView = new ScribbleAdminView();
		$sView->setSource(NULL);
		$GV->attachViewToSlot($sView, 'secondary');

		// Check login
		if(!$bypassAuthCheck && !ScribbleSession::isOccupied()) {
			$view->setSource(Config::get('ext.Scribble.dir.views').'/login.tpl.php');
			$redirect = isset($_POST['redirect']) ? $_POST['redirect'] : (
				isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'
			);
			$view->redirect = $redirect;
			if(isset($_POST['email']) && isset($_POST['password'])) {
				if(($user = ScribbleAuth::authenticate($_POST['email'], $_POST['password']))) {
					ScribbleSession::login($user);
					session_write_close();
					header("Location: {$redirect}");
					exit();
				}
				else {
					SystemLog::add('Login failed. Please try again.', SystemLog::WARNING);
				}
			}
			header("HTTP/1.1 401 Unauthorized");
			return FALSE;
		}

		// Check the "scribble-admin" privilege
		if(!$bypassAuthCheck && !ScribbleAuth::authorize(ScribbleSession::getUser(), 'scribble-admin')) {
			SystemLog::add("Sorry, but you don't have sufficient authority to access this part of the system. Please login under another account.", SystemLog::WARNING);
			return FALSE;
		}

		// Result
		return TRUE;
	}
}
?>